<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">用户登录</h2>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="loginForm.username"
            type="text"
            placeholder="请输入用户名"
            required
            autocomplete="username"
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            required
            autocomplete="current-password"
          />
        </div>
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        <button type="submit" :disabled="loading" class="login-button">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      <div class="demo-info">
        <p>💡 演示模式：任意用户名和密码都可以登录</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { setToken, setUserInfo, type UserInfo } from '../utils/auth'
import { apiApi } from '../request/instances'

const router = useRouter()
const route = useRoute()

const loginForm = ref({
  username: '',
  password: ''
})

const loading = ref(false)
const errorMessage = ref('')

// 处理登录
const handleLogin = async () => {
  loading.value = true
  errorMessage.value = ''

  try {
    // 这里调用实际的登录 API
    // const response = await apiApi.post('/api/login', {
    //   username: loginForm.value.username,
    //   password: loginForm.value.password
    // })

    // 演示模式：模拟登录成功
    // 实际项目中，应该从后端获取 token 和用户信息
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟网络延迟

    // 模拟从后端获取的数据
    const mockToken = `mock_token_${Date.now()}`
    const mockUserInfo: UserInfo = {
      id: 1,
      username: loginForm.value.username,
      email: `${loginForm.value.username}@example.com`,
      roles: ['user']
    }

    // 保存 token 和用户信息
    setToken(mockToken)
    setUserInfo(mockUserInfo)

    console.log('✅ [登录] 登录成功')
    console.log('  Token:', mockToken)
    console.log('  用户信息:', mockUserInfo)

    // 跳转到原目标页面或首页
    const redirect = (route.query.redirect as string) || '/'
    router.push(redirect)
  } catch (error: any) {
    console.error('❌ [登录] 登录失败:', error)
    errorMessage.value = error.message || '登录失败，请检查用户名和密码'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 如果有重定向参数，显示提示
  if (route.query.redirect) {
    console.log('ℹ️ [登录] 需要登录后才能访问:', route.query.redirect)
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px);
  padding: 2rem;
}

.login-box {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 2.5rem;
  width: 100%;
  max-width: 400px;
}

.login-title {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
  font-size: 1.8rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  font-weight: 500;
  color: #333;
  font-size: 0.9rem;
}

.form-group input {
  padding: 0.75rem;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
}

.error-message {
  color: #e74c3c;
  font-size: 0.9rem;
  text-align: center;
  padding: 0.5rem;
  background: #fee;
  border-radius: 6px;
}

.login-button {
  padding: 0.875rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.3s, transform 0.2s;
}

.login-button:hover:not(:disabled) {
  opacity: 0.9;
  transform: translateY(-2px);
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.demo-info {
  margin-top: 1.5rem;
  padding: 1rem;
  background: #f0f4ff;
  border-radius: 8px;
  text-align: center;
}

.demo-info p {
  margin: 0;
  color: #667eea;
  font-size: 0.85rem;
}
</style>

